use serde_json::Value;
use std::fs::File;
use std::io::{self, Read};

#[allow(dead_code)]
pub fn process() -> io::Result<()> {
    let ignore_prefix = vec![
        "/bare-hosts",
        "/disaster",
        "/networkStrategy",
        "/resources",
        "/safety",
        "/stores",
        "/syncVirt",
        "/v2.0",
    ];
    let base_path = "/Users/mojih/Documents/api-doc/api/result";
    let base_file_name = "api_result_v2.json";
    //读取json
    let path = format!("{}/{}", base_path, base_file_name);
    // let mut apis_create: Vec<String> =  Vec::new();
    // Set集合，去重
    let mut apis_create: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut file = File::open(path)?;
    let mut data = String::new();
    file.read_to_string(&mut data)?;
    // 过滤json changeStatus = "create"  apiList-> []
    let mut json_data: Value = serde_json::from_str(&data)?;
    let mut _new_json_data = json_data.clone();
    if let Some(api_list) = json_data.get_mut("apiList") {
        for api in api_list.as_array().unwrap() {
            if let Some(change_status) = api.get("changeStatus") {
                if change_status != "modify" {
                    continue;
                }
                if let Some(api_uri) = api.get("apiURI") {
                    // 去掉开头 去掉 get /post /delete /put_开头
                    // eg:    "apiURI": "get_\/domain\/{domainId}\/log\/export",
                    // split '_'去掉 首个_之前的字符串
                    let left_url = api_uri
                        .as_str()
                        .unwrap()
                        .split('_')
                        .skip(1)
                        .collect::<Vec<&str>>()
                        .join("_");
                    let mut ignore = false;
                    for prefix in ignore_prefix.iter() {
                        if left_url.to_lowercase().starts_with(&prefix.to_lowercase()) {
                            ignore = true;
                            break;
                        }
                    }
                    if ignore {
                        continue;
                        // 跳过
                    }
                    apis_create.insert(format!(
                        "({}){}",
                        api_uri.as_str().unwrap().split('_').collect::<Vec<&str>>()[0],
                        left_url
                    ));
                }
            }
        }
    }
    // 去重
    //去重后的数量
    //排序
    let mut apis_create = apis_create.into_iter().collect::<Vec<String>>();
    apis_create.sort();
    let total = apis_create.len();
    for api in apis_create {
        //第一个 '_' 之前的字符串是method
        //第二个 '_' 之后的字符串是api_name
        let method = api.split('_').collect::<Vec<&str>>()[0];
        // skip first element
        let api_name = api.split('_').skip(1).collect::<Vec<&str>>().join("_");
        println!("{}{}", method, api_name);
    }
    // total
    println!("total:{}", total);
    Ok(())
}
